import {
	defineStore
} from 'pinia'
import {
	login as signIn,
	logout as signOut
} from '@/api/mine'

export const useStore = defineStore('main', {
	state() {
		return {
			tokenInfo: uni.getStorageSync('tokenInfo') ?? null,
			userInfo: uni.getStorageSync('userInfo') ?? null,
			currentAgentInfo: null,
			lsMerInfoSucced: uni.getStorageSync('lsMerInfoSucced') ?? null,
			settleStatus: uni.getStorageSync('settleStatus') ?? null, //是否绑储蓄卡
			account: uni.getStorageSync('account') ?? null,
			permissions: null, // 代理权限: 查看下级字段: channelDetails
			shippingAddressInfo: uni.getStorageSync('shippingAddressInfo') ?? null, // 收货地址信息
			merchantRules: null, // 商户进件规则
			certificationInformation: uni.getStorageSync('certificationInformation') ?? null, // 身份证认证信息
			currentMerchantInfomation: uni.getStorageSync('currentMerchantInfomation') ?? null, // 当前设备信息
			channelInfomation: uni.getStorageSync('channelInfomation') ?? null, //通道信息
		}
	},
	actions: {
		// params参数为对象、数组
		setData(params) {
			Object.keys(params).forEach(key => {
				this[key] = params[key];
			});
		},
		// 清理缓存
		clearStorage() {
			this.tokenInfo = null
			this.userInfo = null
			this.currentAgentInfo = null;
			this.shippingAddressInfo = null;
			this.certificationInformation = null;
			this.lsMerInfoSucced = null;
			this.settleStatus = null;
			uni.removeStorageSync('settleStatus')
			uni.removeStorageSync('tokenInfo')
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('lsMerInfoSucced')
			uni.removeStorageSync('shippingAddressInfo')
			uni.removeStorageSync('certificationInformation')
			uni.removeStorageSync('currentMerchantInfomation')
			uni.removeStorageSync('channelInfomation')
		},
		login(loginInfo) {

			return new Promise((resolve, reject) => {
				signIn(loginInfo).then(res => {
					this.tokenInfo = res.data.data.token

					this.userInfo = res.data.data
					console.log("token=" + JSON.stringify(this.userInfo))
					uni.removeStorageSync('settleStatus')
					uni.removeStorageSync('tokenInfo')
					uni.removeStorageSync('userInfo')
					uni.removeStorageSync('lsMerInfoSucced')
					
					uni.setStorageSync('tokenInfo', this.tokenInfo)
					// uni.setStorageSync('account', profile.phone)
					uni.setStorageSync('userInfo', this.userInfo)
					uni.setStorageSync("lsMerInfoSucced", this.userInfo.lsMerInfoSucced)
					uni.setStorageSync("settleStatus", this.userInfo.settleStatus)
					// console.log("登录保存的userInfo=" + JSON.stringify(uni.getStorageSync(
					// 	'userInfo')))
					uni.navigateTo({
						url: "/pages/index/index",
					});
					return resolve()
				}).catch(error => {
					return reject(error)
				})
			})
		},
		logout() {
			let that = this
			return new Promise((resolve) => {
				let params = {
					token: that.tokenInfo.token
				}
				signOut(params).then(() => {
					this.clearStorage()
					return resolve()
				})
			})
		},
	}
})